<template>
  <view class="bg-[#F3F4F6] c-pd" v-if="state.beeper">
    <view class="bg-white c-br">
      <view class="flex">
        <view class="c-pd"><van-image round width="60px" height="60px" fit="cover" :src="EEquipLogo[1]" /></view>
        <view class="py-12px px-2 flex-1 overflow-hidden">
          <view class="mb-12px flex items-center">
            <view class="c-text-14 pr-2 c-text-ellipsis w-fit">昵称：{{ state.beeper.equipNickName || '未设置' }}</view>
            <i class="i-ri:edit-2-line text-14px c-text-color-grey" @click="showSetEquipPopup('nickName', state.beeper.equipNickName)"></i>
          </view>
          <view v-if="state.real">
            <text>状态：</text>
            <van-tag v-if="state.beeper.equipState === 2" type="success">在线</van-tag>
            <van-tag v-else color="#9C9C9E">离线</van-tag>
            |
            <van-tag v-if="state.beeper.errorState === 1" type="danger">报警</van-tag>
            <van-tag v-else type="success">正常</van-tag>
            <text class="ml-6" v-if="state.beeper.powerLevel">电量：{{ EEquipPower[state.beeper.powerLevel] }}</text>
          </view>
        </view>
      </view>

      <!--设备【实】        <div class="i-ic:baseline-aod w-24px h-24px" style="color: #3638de;"></div>-->
      <view v-if="state.real">
        <view class="px-12px">
          <i class="i-material-symbols-light:location-on-outline-rounded text-4"></i>
          <text class="c-text-14 vertical-mid">{{ siteInfo?.createDate || '' }}{{ siteInfo?.address || '' }}</text>
        </view>
        <view class="px-12px pb-12px" v-if="siteInfo">
          <map :scale="15" :markers="markers" :longitude="Number(siteInfo.longitude)" :latitude="Number(siteInfo.latitude)" class="w-full"></map>
        </view>
      </view>
    </view>
    <view class="text-[14px] font-bold mt-[12px]">{{ state.beeper.beeperType === 1 ? '公共' : '专属' }}呼叫器</view>
    <view class="mt-[12px]">
      <van-cell-group inset>
        <van-cell title="设备编号" :value="state.beeper.equipCode" />
        <van-cell title="设备MAC" :value="state.beeper.equipMac" v-if="state.beeper.equipCode !== state.beeper.equipMac"></van-cell>
        <van-cell title="设备电话号" :value="state.beeper.equipPhone || '无'" v-if="state.real"></van-cell>
        <van-cell title="安装区域" is-link :value="state.beeper.installArea || '未设置'" v-if="state.real" @click="showSetEquipPopup('installArea', state.beeper.installArea)"></van-cell>
        <!--        <van-cell title="余额" :value="state.beeper.powerLevel"></van-cell>-->
        <van-cell title="激活日期" :value="state.beeper.activeDate"></van-cell>
        <van-cell title="流量截止日期" :value="state.beeper.flowEndDate" v-if="state.real"></van-cell>
      </van-cell-group>
    </view>

    <view class="text-[14px] font-bold mt-[12px]">设备地址</view>
    <view class="mt-[12px]">
      <van-cell-group inset>
        <van-cell title="地址" :value="state.address"></van-cell>
        <van-cell title="详细地址" :value="state.fullAddress"></van-cell>
        <van-cell title="联系人" :value="state.beeper.linkName"></van-cell>
        <van-cell title="联系电话" :value="state.beeper.phone"></van-cell>
        <van-cell title="备用电话" is-link :value="state.beeper.phoneTwo || '未设置'" @click="showSetEquipPopup('phoneTwo', state.beeper.phoneTwo)"></van-cell>
      </van-cell-group>
    </view>

    <view class="text-[14px] font-bold mt-[12px]">设备操作</view>
    <view class="grid grid-cols-4 gap-2 c-br c-pd bg-[white] mt-[12px]">
      <view class="flex flex-wrap justify-center items-center" @click="state.showImg = true">
        <i class="i-weui:qr-code-outlined text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 设备码 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.real" @click="handleClickOperate('addressBook')">
        <i class="i-material-symbols-light:contact-phone-outline text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 通讯录 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.beeper.beeperVersion >= 4 && state.beeper.beeperVersion <= 6" @click="handleClickOperate('wechat')">
        <i class="i-material-symbols-light:group-outline text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 微聊好友 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.real" @click="handleClickOperate('startSite')">
        <i class="i-material-symbols-light:distance-outline text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 立即定位 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.beeper.beeperVersion >= 4 && state.beeper.beeperVersion <= 6" @click="showSetEquipPopup('asr', state.beeper.asrSwitch)">
        <i class="i-ic:outline-keyboard-voice text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 语音识别 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.real" @click="showSetEquipPopup('low', state.beeper.lowFlag)">
        <i class="i-material-symbols-light:battery-charging-20 text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 低电提醒 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" v-if="state.beeper.errorState === 1" @click="handleClickOperate('cancelAlarm')">
        <i class="i-material-symbols-light:notifications-off-outline-sharp text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 解除报警 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" @click="handleClickOperate('alarmRecord')">
        <i class="i-material-symbols-light:circle-notifications-outline text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 报警记录 </view>
      </view>
      <view class="flex flex-wrap justify-center items-center" @click="handleClickOperate('unbindEquip')">
        <i class="i-material-symbols-light:delete-forever-outline-sharp text-[36px]" />
        <view class="mt-[8px] w-[100%] text-center c-text-12"> 解绑设备 </view>
      </view>
    </view>
  </view>

  <van-popup width :show="state.showImg" @close="state.showImg = false">
    <van-image width="240px" height="240px" fit="cover" :src="state.beeper?.wxAppUrl" />
  </van-popup>

  <SetEquipInfoPopup v-if="state.beeper" :equip-id="state.beeper.equipId" :relation-id="state.beeper.relationId" :type="setInfo.type" :content="setInfo.content" @change-value="handleChangeValue" />
</template>

<script setup lang="ts">
import EquipRequest from '@/request/equipRequest';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import { EEquipLogo, EEquipPower } from '@/enum/equip';
import SetEquipInfoPopup from '@/subcontract/equipment/equipDetail/component/SetEquipInfoPopup.vue';
import { useControllerStore } from '@/store';
import { navigate } from '@/utils/navigate';

interface IProps {
  beeperId: number;
}
interface IState {
  showImg: boolean;
  real: boolean; //是否实体呼叫器
  address: string;
  fullAddress: string;
  beeper?: IBeeperDetailRes;
}

const props = defineProps<IProps>();
const state = reactive<IState>({ showImg: false, real: true, address: '', fullAddress: '' });
const setInfo = reactive<{ type: string; content: any }>({ type: '', content: '' });
const { showModal } = useModal();
const { showToast } = useToast();
const siteInfo = ref<IGetSiteNow>();
const markers = ref<{ id: number; longitude: number; iconPath: string; latitude: number; width: number; height: number }[]>([
  {
    id: 0,
    longitude: 0,
    iconPath: '',
    latitude: 0,
    width: 26,
    height: 30,
  },
]);

onMounted(() => {
  getBeeperInfo();
});

const getBeeperInfo = () => {
  EquipRequest.GetBeeperDetail({ id: props.beeperId, hasLoading: true }).then((res) => {
    state.beeper = res.data;
    state.real = res.data.beeperVersion != 1;
    state.address = (res.data.provinceName || '') + (res.data.cityName || '') + (res.data.areaName || '') + (res.data.streetName || '');
    if (res.data.address && res.data.address !== '待补充') {
      state.fullAddress = res.data.address;
    } else {
      state.fullAddress = (res.data.villageName || '') + (res.data.buildName || '') + (res.data.unitName || '') + (res.data.floorName || '') + (res.data.houseNumber || '');
    }
    if (state.real) {
      getSiteNow(res.data.equipId);
    }
  });
};
const getSiteNow = (equipId: number) => {
  EquipRequest.GetSiteNow({ equipId: equipId }).then((res) => {
    if (res.data) {
      siteInfo.value = res.data;
      markers.value[0].longitude = siteInfo.value!.longitude === null ? 0 : Number(siteInfo.value!.longitude);
      markers.value[0].latitude = siteInfo.value!.latitude === null ? 0 : Number(siteInfo.value!.latitude);
    }
  });
};

const showSetEquipPopup = (type: string, content: any) => {
  setInfo.type = type;
  setInfo.content = content;
  useControllerStore().$patch({ setEquipInfoPopup: true });
};

const handleChangeValue = (payload: { type: string; content: any }) => {
  if (!state.beeper) return;
  switch (payload.type) {
    case 'nickName':
      state.beeper.equipNickName = payload.content;
      break;
    case 'phoneTwo':
      state.beeper.phoneTwo = payload.content;
      break;
    case 'installArea':
      state.beeper.installArea = payload.content;
      break;
  }
};

const handleClickOperate = (type: string) => {
  switch (type) {
    case 'alarmRecord':
      navigate({ url: '/subcontract/equipment/equipDetail/viewAlarmRecords?equipId=' + state.beeper?.equipId });
      break;
    case 'wechat':
      navigate({ url: '/subcontract/equipment/addressBook/setWechat?beeperId=' + state.beeper?.beeperId });
      break;
    case 'addressBook':
      navigate({ url: '/subcontract/equipment/addressBook/index?equipId=' + state.beeper?.equipId + '&equipType=1' });
      break;
    case 'startSite':
      EquipRequest.EquipStartSite({ equipId: state.beeper?.equipId }).then((res) => {
        showToast('定位成功', 'success');
        setTimeout(() => {
          getSiteNow(<number>state.beeper?.equipId);
        }, 1000 * 60);
      });
      break;
    case 'cancelAlarm':
      showModal('确定解除警报吗？', {
        showCancel: true,
        cancelText: '误触发',
        confirmText: '已处理',
        success: (res) => {
          EquipRequest.CancelEquipAlarm({ equipId: state.beeper?.equipId, cancelReason: res.confirm ? 2 : 1 }).then((res) => {
            showToast('警报已解除', 'success');
          });
        },
      });
      break;
    case 'unbindEquip':
      showModal('是否解绑当前设备？', {
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            EquipRequest.UnbindingEquip({ id: state.beeper?.equipId }).then((res) => {
              showToast('解绑成功', 'success');
              setTimeout(() => {
                navigate({ url: '', type: 'navigateBack' });
              }, 1000);
            });
          }
        },
      });
      break;
  }
};
</script>
